The CMPXCHG (Compare-Exchange) operation is commonly used as one instruction in a sequence of instructions to form a critical section around a region of code (i.e., instructions, operations, etc.). It allows the region of code to execute atomically. A set of instructions may be considered atomic when two conditions are met: first, until the entire set of instructions completes, no other process can know about the changes being made, and second, if any of the instructions in the set fail then the entire set of instructions fails. When the entire set of instructions fails, the state of the computer system executing the instructions is restored to the state it was in before any of the instructions began. In some embodiments, the CMPXCHG instruction may be thought of as a software-defined wrapper of the region of code with the critical section. In other words, this wrapper can be designed into software code, but it is not a wrapper in the sense that it is enforced by hardware as such.
The CMPXCHG instruction assists sets of instructions to be executed atomically by checking to make sure a value retrieved from memory at the beginning of the atomic set has not been modified by another process during the execution of the set of instructions. For example, if a value in a specific location in memory is loaded into a register at the start of the atomic set of instructions, after the set of instructions has completed there may be a request to load a new (i.e., modified) value back into the original memory location (the modified value being the result of the set of instructions).
The CMPXCHG instruction can be utilized at the end of the atomic set of instructions to check to see if the value originally loaded from the particular memory location is still there in that location in memory (i.e., not modified by another process or thread at some point during the execution of the atomic set of instructions). If the original value is still there, then the CMPXCHG instruction loads the new value into the particular memory location that was storing the old value and the atomic set of instructions successfully completes. If the original value is not there, which means another process or thread did modify the value during the execution of the atomic set of instructions, then the CMPXCHG instruction does not load the new value into the particular memory location, notifies the system of this, and as a result of the notification, there may be a conditional jump implemented in the code to jump up to the beginning of the atomic set of instructions for another attempt at successful completion.